const _ = require('lodash');
const uuidv4 = require('uuid/v4');
var fs = require('fs');
var request = require('request');
var fileServerConfig = require('../../app.config/env/fileServer.config');
var dishService = require('../service/dish.service');

module.exports = {
    findById: findById,
    findByType: findByType,
    findByName: findByName,
    findByBoth: findByBoth,
    findAll: findAll,
    addDish: addDish,
    deleteDish: deleteDish,
    updateDish: updateDish
};

/**
 * findById
 * @param req
 * @param res
 * @param next
 */
function findById(req, res, next) {
    var did = req.params.did;
    if (_.isEmpty(did)) {
        res.json({result: false, errMsg: 'dish id is empty'});
    } else {
        dishService.findById(did, function (err, data) {
            if (err) {
                res.json({result: false, errMsg: 'can not find the dish'});
            } else {
                res.json({result: true, data: data});
            }
        });
    }
}

/**
 * findByType
 * @param req
 * @param res
 * @param next
 */
function findByType(req, res, next) {

    var mid = req.session.merchant._id;

    var type = req.params.type;

    if (_.isEmpty(mid)) {
        res.json({result: false, errMsg: 'mid is empty'});
    } else {
        if (type == '所有类型') {
            dishService.findByMid(mid, function (err, data) {
                if (err) {
                    res.json({result: false, errMsg: 'can not find the dish'});
                } else {
                    res.json({result: true, data: data});
                }
            });
        } else {
            dishService.findByType(mid, type, function (err, data) {
                if (err) {
                    res.json({result: false, errMsg: 'can not find the dish'});
                } else {
                    res.json({result: true, data: data});
                }
            });
        }
    }
}

/**
 * findByName
 * @param req
 * @param res
 * @param next
 */
function findByName(req, res, next) {
    var name = req.params.name;
    const nameRe = new RegExp(name, 'i');
    var mid = req.session.merchant._id;
    if (_.isEmpty(mid)) {
        res.json({result: false, errMsg: 'mid is empty'});
    } else {
        dishService.findByName(mid, nameRe, function (err, data) {
            if (err) {
                res.json({result: false, errMsg: 'can not find the dish'});
            } else {
                res.json({result: true, data: data});
            }
        });
    }
}

/**
 * findByBoth
 * @param req
 * @param res
 * @param next
 */
function findByBoth(req, res, next) {

    var mid = req.session.merchant._id;

    var name = req.params.name;
    const nameRe = new RegExp(name, 'i');
    var type = req.params.type;

    if (_.isEmpty(mid)) {
        res.json({result: false, errMsg: 'mid is empty'});
    } else {
        if (type == "所有类型") {
            if (name == 'undefined') {
                dishService.findByMid(mid, function (err, data) {
                    if (err) {
                        res.json({result: false, errMsg: 'can not find the dish'});
                    } else {
                        res.json({result: true, data: data});
                    }
                });
            } else {
                dishService.findByName(mid, nameRe, function (err, data) {
                    if (err) {
                        res.json({result: false, errMsg: 'can not find the dish'});
                    } else {
                        res.json({result: true, data: data});
                    }
                });
            }
        } else {
            if (name == 'undefined') {
                dishService.findByType(mid, type, function (err, data) {
                    if (err) {
                        res.json({result: false, errMsg: 'can not find the dish'});
                    } else {
                        res.json({result: true, data: data});
                    }
                });
            } else {
                dishService.findByBoth(mid, type, nameRe, function (err, data) {
                    if (err) {
                        res.json({result: false, errMsg: 'can not find the dish'});
                    } else {
                        res.json({result: true, data: data});
                    }
                });
            }
        }
    }
}

/**
 * findAll
 * @param req
 * @param res
 * @param next
 */
function findAll(req, res, next) {

    var mid = req.session.merchant._id;

    if (_.isEmpty(mid)) {
        res.json({result: false, errMsg: 'mid is empty'});
    } else {
        dishService.findByMid(mid, function (err, data) {
            if (err) {
                res.json({result: false, errMsg: 'can not find the dish'});
            } else {
                res.json({result: true, data: data});
            }
        });
    }
}

/**
 * addDish
 * @param req
 * @param res
 * @param next
 */
function addDish(req, res, next) {
    console.log("__dirname:" + __dirname);
    var body = req.body;
    var dish = {};
    var response = {};

    var m = req.session.merchant;
    dish.mid = req.session.merchant._id;

    dish._id = uuidv4();
    dish.name = body.name;
    dish.type = body.type;
    dish.price = body.price;
    var dishImgPath = "dish/" + dish._id + ".jpg";
    var files = req.files;
    var imgName = files.dishImg.name;
    var imgs = [];
    var dishBuf = fs.readFileSync(__dirname + '/../../uploads/' + imgName);
    imgs.push({filename: dishImgPath, file: dishBuf.toString('base64')});
    dish.img = dishImgPath;

    request.post({url: fileServerConfig.fileServer.url, form: {"files": imgs}}, function (err, httpResponse, body) {
        if (err) {
            res.json({result: false, code: constant.ServerDown, errMsg: 'server is down'});
        } else {
            //insect into db
            console.log("insert:" + JSON.stringify(dish));
            dishService.addDish(dish, function (err, doc) {
                if (err) {
                    res.json({result: false, errMsg: 'insert into DB failed'});
                } else {
                    res.json({result: true, data: doc});
                }
            });
        }
        fs.unlink(__dirname + '/../../uploads/' + imgName);
    });
}

/**
 * deleteDish
 * @param req
 * @param res
 * @param next
 */
function deleteDish(req, res, next) {
    var id = req.params.id;
    if (_.isEmpty(id)) {
        res.json({result: false, errMsg: 'the id of dish wanted to delete is empty'});
    } else {
        dishService.deleteDish(id, function (err, data) {
            if (err) {
                res.json({result: false, errMsg: 'can not delete the dish'});
            } else {
                res.json({result: true, data: data});
            }
        })
    }
}

/**
 * updateDish
 * @param req
 * @param res
 * @param next
 */
function updateDish(req, res, next) {
    console.log("__dirname:" + __dirname);
    var body = req.body;
    var dish = {};

    dish.mid = req.session.merchant._id;

    dish._id = body.did;
    dish.name = body.name;
    dish.type = body.type;
    dish.price = new Number(body.price);
    var dishImgPath = "dish/" + dish._id + ".jpg";
    var files = req.files;


    if (!files.dishImg) {
        console.log("update:" + JSON.stringify(dish));
        dishService.updateDish(dish, function (err, doc) {
            if (err) {
                res.json({result: false, errMsg: 'update failed'});
            } else {
                res.json({result: true, data: doc});
            }
        });
    } else {
        var imgName = files.dishImg.name;
        var imgs = [];
        var dishBuf = fs.readFileSync(__dirname + '/../../uploads/' + imgName);
        imgs.push({filename: dishImgPath, file: dishBuf.toString('base64')});
        dish.img = dishImgPath;

        request.post({url: fileServerConfig.fileServer.url, form: {"files": imgs}}, function (err, httpResponse, body) {
            if (err) {
                res.json({result: false, code: constant.ServerDown, errMsg: 'server is down'});
            } else {
                //insect into db
                console.log("update:" + JSON.stringify(dish));
                dishService.updateDish(dish, function (err, doc) {
                    if (err) {
                        res.json({result: false, errMsg: 'update failed'});
                    } else {
                        res.json({result: true, data: doc});
                    }
                });
            }
            fs.unlink(__dirname + '/../../uploads/' + imgName);
        });
    }


    // var imgName = files.dishImg.name;
    // var imgs = [];
    // var dishBuf = fs.readFileSync(__dirname + '/../../uploads/' + imgName);
    // imgs.push({filename: dishImgPath, file: dishBuf.toString('base64')});
    // dish.img = dishImgPath;
    //
    // request.post({url: fileServerConfig.fileServer.url, form: {"files": imgs}}, function (err, httpResponse, body) {
    //     if (err) {
    //         res.json({result: false, code: constant.ServerDown, errMsg: 'server is down'});
    //     } else {
    //         //insect into db
    //         console.log("update:" + JSON.stringify(dish));
    //         dishService.updateDish(dish, function (err, doc) {
    //             if (err) {
    //                 res.json({result: false, errMsg: 'update failed'});
    //             } else {
    //                 res.json({result: true, data: doc});
    //             }
    //         });
    //     }
    //     fs.unlink(__dirname+'/../../uploads/'+imgName);
    // });
}


//
// var callBack = function (err, data) {
//     if (err) {
//         res.json({result: false, errMsg: 'can not find the dish'});
//     } else {
//         res.json({result: true, data: data});
//     }
// }



